<?php

namespace App\Model\Member;

use Illuminate\Database\Eloquent\Model;

class MemberMoney extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'member_money';

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = false;

    /**
     *
     * 使用/充值余额
     *
     * @param $uid 用户ID
     * @param $price 金额
     * @param $action 使用/充值区分（1为使用，2为充值）
     * @param $note 说明
     * @param int $payment 支付渠道
     * @return bool 是否成功
     */
    public static function useMoney($uid, $price, $action, $note, $payment = 0){
        $member = Member::find($uid);
        # 判断$action是收入还是支出，来判断用户表的余额是增是减，如果是支出($action == 1)，查看一下余额是否充足
        if($action == 1){
            if($price > $member->money){
                return false;
            }
            $member->money -= $price;
            # 余额使用记录里，要保存负值
            $price = 0 - $price;
        }
        elseif ($action == 2){
            $member->money += $price;
        }
        # 修改Member表money字段数值
        if(!$member->save()){
            return false;
        }
        # 添加余额使用记录表
        $data = [
            'member_id' => $uid,
            'action' => $action,
            'payment' => $payment,
            'number' => $price,
            'note' => $note,
            'create_time' => currentTime(),
        ];
        $result = self::insert($data);
        if(!$result){
            return false;
        }
        return true;
    }
}
